# -*- coding: utf-8 -*-
import frappe
from frappe.utils import flt, cint, cstr, getdate, nowdate, add_days, add_months, add_years, get_first_day, get_last_day

def get_fiscal_year(date=None):
    """获取财政年度"""
    if not date:
        date = nowdate()
    
    fiscal_year = frappe.db.sql("""
        SELECT name, year_start_date, year_end_date
        FROM `tabFiscal Year`
        WHERE %s BETWEEN year_start_date AND year_end_date
        AND docstatus = 1
    """, date, as_dict=True)
    
    if fiscal_year:
        return fiscal_year[0]
    else:
        # 如果没有找到财政年度，返回基于日期的默认值
        date_obj = getdate(date)
        year = date_obj.year
        if date_obj.month >= 4:  # 假设财政年度从4月开始
            return {
                "name": f"{year}-{year+1}",
                "year_start_date": f"{year}-04-01",
                "year_end_date": f"{year+1}-03-31"
            }
        else:
            return {
                "name": f"{year-1}-{year}",
                "year_start_date": f"{year-1}-04-01",
                "year_end_date": f"{year}-03-31"
            }

def get_account_balance(account, company, posting_date=None):
    """获取账户余额"""
    if not posting_date:
        posting_date = nowdate()
    
    balance = frappe.db.sql("""
        SELECT SUM(debit) - SUM(credit) as balance
        FROM `tabGL Entry`
        WHERE account = %s
        AND company = %s
        AND posting_date <= %s
        AND is_cancelled = 0
    """, (account, company, posting_date), as_dict=True)
    
    return flt(balance[0].balance) if balance else 0

def get_account_type(account):
    """获取账户类型"""
    account_type = frappe.db.get_value("Account", account, "account_type")
    return account_type or ""

def is_debit_account(account):
    """判断是否为借方账户"""
    account_type = get_account_type(account)
    return account_type in ["Asset", "Expense", "Cost of Goods Sold", "Fixed Asset"]

def is_credit_account(account):
    """判断是否为贷方账户"""
    account_type = get_account_type(account)
    return account_type in ["Liability", "Equity", "Income", "Capital Account"]

def format_amount(amount, precision=2):
    """格式化金额"""
    return flt(amount, precision)

def validate_accounting_period(posting_date, company):
    """验证会计期间"""
    accounting_period = frappe.db.sql("""
        SELECT name, start_date, end_date
        FROM `tabAccounting Period`
        WHERE company = %s
        AND %s BETWEEN start_date AND end_date
        AND docstatus = 1
    """, (company, posting_date), as_dict=True)
    
    if not accounting_period:
        frappe.throw(f"日期 {posting_date} 不在任何有效的会计期间内")
    
    return accounting_period[0]